package com.yh.yhso.datasource;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yh.yhso.common.ErrorCode;
import com.yh.yhso.exception.BusinessException;
import com.yh.yhso.model.entity.Picture;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图片服务实现
 * <p>
 * YH
 */
@Service
@Slf4j
public class PictureDataSource implements DataSource<Picture> {

    @Override
    public Page<Picture> doSearch(String searchText, long pageNum, long pageSize) {
        List<Picture> pictures = new ArrayList<>();
        // 请求地址
        long current = (pageNum - 1) * pageSize;
        String url = String.format("https://cn.bing.com/images/search?q=%s&first=%s", searchText, current);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片数据获取异常");
        }
        Elements elements = doc.select(".iuscp.isv");
        for (Element element : elements) {
            // 取图片地址（murl）
            String img = element.select(".iusc").get(0).attr("m");
            Map<String, Object> urlMap = JSONUtil.toBean(img, Map.class);
            String img_url = (String) urlMap.get("murl");
            // 取标题
            String title = element.select(".inflnk").get(0).attr("aria-label");
            // 存到pictureList
            pictures.add(new Picture(img_url, title));
            // 查询的数量够了
            if (pictures.size() >= pageSize) {
                break;
            }
        }
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures);
        return picturePage;
    }

}




